﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SIS_Wcf_Server;

namespace SIS_Wcf_Server.SpotFinder
{
    public class Indexer
    {

        static Indexer idx;
        Model.IData _data;

        System.Threading.Thread thread;


        private Indexer( )
        {
            _data = new Model.EfData();
            thread = new System.Threading.Thread(new System.Threading.ThreadStart(Run));

            thread.Start();
            
        }

        public static void Init()
        {
            idx = new Indexer();
        }

        private void Run()
        {
            int ilastamount = 0;
            while (true)
            {
                List<Model.net> data = _data.GetLatestNets();

                if ( data.Count > ilastamount )
                {

                    foreach (var loc in _data.GetLatestNets())
                    {
                        if (loc.gpsPositioner.Count > 0)
                        {
                            // We got the basics to calculate a "approximated center" for the given net.
                            Model.geocoded_nets approxLocation = new Model.geocoded_nets();

                            approxLocation.Id = Guid.NewGuid();

                            double lat = 0.0;
                            double lng = 0.0;

                            foreach (var gps in loc.gpsPositioner)
                            {
                                lat += gps.Lat == null ? 0.0 : (double)gps.Lat;
                                lng += gps.Long == null ? 0.0 : (double)gps.Long; ;
                            }

                            lat /= loc.gpsPositioner.Count;
                            lng /= loc.gpsPositioner.Count;

                            approxLocation.Lat = lat;
                            approxLocation.Long = lng;

                            loc.geocoded_nets.Clear();

                            loc.geocoded_nets.Add(approxLocation);

                            _data.store();
                        }
                    }
                }
                System.Threading.Thread.Sleep( 15000 );
            }

        }


    }
}